/* $Id: linux.c,v 1.1 2005/06/20 16:34:28 jfb Exp $ */
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <jfb@openbsd.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * strlcpy and strlcat license:
 *
 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/queue.h>
#include <sys/socket.h>

#include <net/if.h>

#include <net/if_arp.h>

#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "if.h"
#include "dlink.h"
#include "pforge.h"

#define PFIF_NBIF_INIT  24
#define PFIF_NBIF_INCR  10



static PF_NETIF* pf_netif_fromifreq    (int, struct ifreq *);

static int       pf_netif_xlateflags (int);


/*
 * pf_netif_probe()
 *
 * Probe the system through the appropriate interface to rebuild the library's
 * view of the system's available interfaces.
 * Returns the number of interfaces found on success, or -1 on failure.
 */
int
pf_netif_probe(void)
{
	int nbif, sfd, ifblen, pifblen;
	size_t len;
	caddr_t ifptr;
	struct ifconf ifc;
	PF_NETIF *nif;
	struct ifreq *ifr;

	sfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sfd < 0) {
		return (-1);
	}

	/*
	 * Try ioctl's until we get all interfaces.
	 * on Solaris, a SIOCGIFCONF ioctl will return EINVAL if the buffer
	 * of the ifconf structure is not large enough, while BSD systems
	 * will fill it with as much info as it can before it's full.
	 *
	 * On Linux, SIOCGIFCONF only returns the list of interfaces which have
	 * an IP address set.  This is somewhat annoying, as the only other way
	 * I have found to gather the information is through the /proc
	 * filesystem.
	 *
	 * In any cases, we start with a really big buffer to avoid some obscure
	 * problems.
	 */
	pifblen = 0;
	ifblen = 8192;
	for (;;) {
		ifc.ifc_buf = malloc(ifblen);
		if (ifc.ifc_buf == NULL) {
			return (-1);
		}

		ifc.ifc_len = ifblen;
		if (ioctl(sfd, SIOCGIFCONF, &ifc) < 0) {
			free(ifc.ifc_buf);
			return (-1);
		}
		if (ifc.ifc_len <= ifblen)
			break;
		free(ifc.ifc_buf);
		ifblen *= 2;
	}

	nbif = 0;
	for (ifptr = ifc.ifc_buf; ifptr < ifc.ifc_buf + ifc.ifc_len;) {
		ifr = (struct ifreq *)ifptr;
		printf("loading `%s' (%d)\n", ifr->ifr_name,
		    ifr->ifr_addr.sa_family);

		len = sizeof(struct ifreq);
		ifptr += len;

		nif = pf_netif_fromifreq(sfd, ifr);

		if (pf_netif_add(nif, nif->if_index) < 0) {
			return (-1);
		}
		nbif++;
	}

	free(ifc.ifc_buf);
	(void)close(sfd);

	return (nbif);
}


static int
pf_netif_xlateflags(int flags)
{
	int i, ret = 0;

	for (i = 0; i < (int)(sizeof(flags) * 8); i++)
		if (flags & (1 << i))
			ret |= pf_netif_fltab[i];

	return (ret);
}

/*
 * pf_netif_fromifreq()
 *
 * Gather the necessary information about a particular network interface
 * represented by <ifr> and create a system-independent pf_if structure
 * containing all the information.  The caller must somehow free the
 * allocated structure.
 * Returns a pointer to the allocated pf_if structure, or NULL on failure.
 */

static PF_NETIF*
pf_netif_fromifreq(int sock, struct ifreq *ifr)
{
	PF_NETIF *nif;
	struct ifreq ifrcp;

	nif = pf_netif_alloc();
	if (nif == NULL) {
		return (NULL);
	}
	strlcpy(nif->if_name, ifr->ifr_name, sizeof(nif->if_name));

	memcpy(&ifrcp, ifr, sizeof(ifrcp));
	if (ioctl(sock, SIOCGIFFLAGS, &ifrcp) == -1) {
	}
	nif->if_flags = pf_netif_xlateflags(ifrcp.ifr_flags);

	/* get the hardware address */
	strlcpy(ifrcp.ifr_name, nif->if_name, sizeof(ifrcp.ifr_name));
	if (ioctl(sock, SIOCGIFHWADDR, &ifrcp) == -1) {
	}
	memcpy(nif->ifhwaddr, ifr->ifr_hwaddr.sa_data,
	    sizeof(nif->ifhwaddr));

	switch (ifr->ifr_hwaddr.sa_family) {
	case ARPHRD_ETHER:
	case ARPHRD_EETHER:
		nif->if_type = PFIF_TYPE_ETHER;
		nif->if_hwalen = 6;
		break;

	case ARPHRD_LOOPBACK:
		nif->if_type = PFIF_TYPE_LOOP;
		break;

	case ARPHRD_FDDI:
		nif->if_type = PFIF_TYPE_FDDI;
		break;

	case ARPHRD_IEEE80211:
		nif->if_type = PFIF_TYPE_IEEE80211;
		break;

	default:
		nif->if_type = PFIF_TYPE_OTHER;
		break;
	}

	if (ioctl(sock, SIOCGIFMTU, &ifrcp) == -1) {
		nif->if_mtu = 0;
	} else {
		nif->if_mtu = ifrcp.ifr_mtu;
	}

	if (ioctl(sock, SIOCGIFINDEX, &ifrcp) == -1) {
	}
	else {
		nif->if_index = ifrcp.ifr_ifindex;
	}

	return (nif);
}

/*
 * Appends src to string dst of size siz (unlike strncat, siz is the
 * full size of dst, not space left).  At most siz-1 characters
 * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
 * Returns strlen(src) + MIN(siz, strlen(initial dst)).
 * If retval >= siz, truncation occurred.
 */
size_t
strlcat(char *dst, const char *src, size_t siz)
{
	char *d = dst;
	const char *s = src;
	size_t n = siz;
	size_t dlen;

	/* Find the end of dst and adjust bytes left but don't go past end */
	while (n-- != 0 && *d != '\0')
		d++;
	dlen = d - dst;
	n = siz - dlen;

	if (n == 0)
		return(dlen + strlen(s));
	while (*s != '\0') {
		if (n != 1) {
			*d++ = *s;
			n--;
		}
		s++;
	}
	*d = '\0';

	return(dlen + (s - src));	/* count does not include NUL */
}

/*
 * Copy src to string dst of size siz.  At most siz-1 characters
 * will be copied.  Always NUL terminates (unless siz == 0).
 * Returns strlen(src); if retval >= siz, truncation occurred.
 */
size_t
strlcpy(char *dst, const char *src, size_t siz)
{
	char *d = dst;
	const char *s = src;
	size_t n = siz;

	/* Copy as many bytes as will fit */
	if (n != 0 && --n != 0) {
		do {
			if ((*d++ = *s++) == 0)
				break;
		} while (--n != 0);
	}

	/* Not enough room in dst, add NUL and traverse rest of src */
	if (n == 0) {
		if (siz != 0)
			*d = '\0';		/* NUL-terminate dst */
		while (*s++)
			;
	}

	return(s - src - 1);	/* count does not include NUL */
}
